package com.ronghuanet.order.service.impl;

import com.ronghuanet.aftermarket.domain.Guarantee;
import com.ronghuanet.aftermarket.mapper.GuaranteeMapper;
import com.ronghuanet.finance.domain.Deposit;
import com.ronghuanet.finance.domain.Receivables;
import com.ronghuanet.finance.domain.ReceivablesItem;
import com.ronghuanet.finance.mapper.DepositMapper;
import com.ronghuanet.finance.mapper.ReceivablesItemMapper;
import com.ronghuanet.finance.mapper.ReceivablesMapper;
import com.ronghuanet.order.domain.Contract;
import com.ronghuanet.order.domain.Order;
import com.ronghuanet.order.dto.OrderPayDto;
import com.ronghuanet.order.mapper.ContractMapper;
import com.ronghuanet.order.mapper.OrderMapper;
import com.ronghuanet.order.service.IOrderService;
import com.ronghuanet.basic.service.impl.BaseServiceImpl;
import com.ronghuanet.org.domain.Employee;
import com.ronghuanet.product.domain.Product;
import com.ronghuanet.product.mapper.ProductMapper;
import com.ronghuanet.sysmanage.domain.Dictionaryitem;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-08-26
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DepositMapper depositMapper;
    @Autowired
    private GuaranteeMapper guaranteeMapper;

    @Autowired
    private ReceivablesMapper receivablesMapper;
    @Autowired
    private ReceivablesItemMapper receivablesItemMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Override
    @Transactional
    public void pay(OrderPayDto orderPayDto) {
        Long orderId= orderPayDto.getOrderId();
        //获取数据字典明细-分期年限
        Dictionaryitem payModel = orderPayDto.getPayModel();
        Order order = orderMapper.loadById(orderId);
        //获取产品信息
        Product product = productMapper.loadById(order.getProductId());
        //查询出定金
        Deposit deposit = depositMapper.loadByOrderSn(order.getSn());
        //创建合同
        Contract contract = new Contract();
        contract.setSn(UUID.randomUUID().toString());
        contract.setOrderId(orderId);
        contract.setOrderSn(order.getSn());
        contract.setCustomerId(order.getCustomerId());
        contract.setCustomerName(order.getCustomerName());
        contract.setPrice(order.getPrice());
        if (deposit!=null)
            contract.setDeposit(new BigDecimal(deposit.getDeposit()));
        contract.setContent(order.getCustomerName()+"花费"+contract.getPrice()+"买了"+order.getProductName());
        contract.setCreateTime(new Date());
        contract.setState(1);
        contractMapper.save(contract);
        //创建保修单及明细  - 只有保修单，没有明细
        Guarantee guarantee = new Guarantee();
        guarantee.setProductId(product.getId());
        guarantee.setProductName(product.getName());
        guarantee.setOrderId(orderId);
        guarantee.setOrderSn(order.getSn());
        guarantee.setCustomerId(order.getCustomerId());
        guarantee.setCustomerName(order.getCustomerName());
        guarantee.setStartTime(new Date());
        guarantee.setEndTime(DateUtils
                .addMonths(new Date(), 36)); //保质期36月
        guarantee.setState(1); //1有效期内 -1 过期了
        guaranteeMapper.save(guarantee);
        //创建应收款
        Receivables receivables = new Receivables();
        receivables.setContractId(contract.getId());
        receivables.setCustomerId(order.getCustomerId());
        receivables.setCustomerName(order.getCustomerName());
        receivables.setProductId(order.getProductId());
        receivables.setProductName(order.getProductName());
        receivables.setPrice(order.getPrice());
        receivables.setPaymentMethodId(payModel.getId());
        receivables.setCreateTime(new Date());
        receivablesMapper.save(receivables);
        //处理应收款明细
        handleReceivablesItem(payModel, order, product, contract, receivables,orderPayDto.getLoginUser());
        //修改订单状态
        order.setState(2);
        orderMapper.update(order);
    }

    private void handleReceivablesItem(Dictionaryitem payModel, Order order, Product product,
                                       Contract contract, Receivables receivables,Employee loginUser) {
        //定金也是应收款，只是已经收了
        if (contract.getDeposit().longValue()>0)
            addReceivablesItem(payModel, product, contract, receivables,contract.getDeposit(),loginUser,1);

        //判断是否是全款
        Integer payNum = Integer.valueOf(payModel.getValue())*12;
        BigDecimal payMoney = order.getPrice()
                .subtract(contract.getDeposit());
        if (payNum ==0){
            addReceivablesItem(payModel, product, contract, receivables,payMoney,loginUser,1);
        }else{
            for (int i = 1; i <= payNum; i++) {
                BigDecimal payMoneyByMonth = payMoney.divide(new BigDecimal(payNum));
                addReceivablesItem(payModel, product, contract,receivables,payMoneyByMonth,null,0);
            }
        }
    }

    private void addReceivablesItem(Dictionaryitem payModel, Product product,
                                    Contract contract, Receivables receivables, BigDecimal price, Employee payee, Integer state) {
        //创建应收款明细
        ReceivablesItem receivablesItem = new ReceivablesItem();
        receivablesItem.setReceivablesId(receivables.getId());
        receivablesItem.setName("收到"+contract.getCustomerName()+":"+price);//应收账款明细名称，暂缓设置
        receivablesItem.setContractId(contract.getId());
        receivablesItem.setCustomerId(contract.getCustomerId());
        receivablesItem.setCustomerName(contract.getCustomerName());
        receivablesItem.setProductId(product.getId());
        receivablesItem.setProductName(product.getName());
        receivablesItem.setPrice(price);
        receivablesItem.setPaymethodId(payModel.getId());
        if (state==1) //已经支付了才有支付时间
             receivablesItem.setPayTime(new Date());
        //receivablesItem.setLastShouldPayTime();
        receivablesItem.setReceivablesId(receivables.getId());
        receivablesItem.setState(state);//0：未收  1：收取
        if (payee!=null){
            receivablesItem.setPayee(payee.getId());//收款人
            receivablesItem.setPayeeName(payee.getUsername());
        }
        receivablesItemMapper.save(receivablesItem);
    }
}
